package com.fingard.diagnostics;

import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.constant.Format;

public class StartLog {
	public StartLog(){
		sbLog = new StringBuffer(2048);
	}
	
	/**存系统启动日志*/
	private StringBuffer sbLog;
	
	/**添加启动日志专用
	 * 注意！启动日志专用*/
	public void addLog(String pLog){
		addLog(pLog, true, true);
	}
	/**添加启动日志专用，不加时间
	 * 注意！启动日志专用*/
	public void addLogNoTime(String pLog){ 
		addLog(pLog, false, true);
	}
	
	/**不输出控制台*/
	public void addNoConsole(String pLog){
		addLog(pLog, false, false);
	}
	
	/**同时添加到limitMsg*/
	public void addToLimit(String logCode, String msg){
		FGBiz.limitMsg.addConsole(logCode, msg);
		addLog(msg, true, false);
	}
	
	public void addToLimitNoConsole(String logCode, String msg){
		FGBiz.limitMsg.addNoConsole(logCode, msg);
		addLog(msg, false, false);
	}
	
	/**错误，同时添加到limitMsg*/
	public void error(String logCode, String msg){
		FGBiz.limitMsg.error(logCode, msg);
		String strLog = "---error--"+Format.DateTimeSSSFormat.format(new Date())+"---\r\n" +logCode+"\t" + msg + "---------------------\r\n";
		addLog(strLog, false, false);
	}
	
	/**异常，同时添加到limitMsg*/
	public void exception(String logCode, Throwable e, String... p_values){
		FGBiz.limitMsg.exception(logCode, e, p_values);
		StringBuilder sbMsg = new StringBuilder();
		if(p_values != null){
			for (int i = 0; i < p_values.length; i++) {
				sbMsg.append("\t");
	            sbMsg.append(p_values[i]);
	        }
		}
		sbMsg.append(LogHelper.getStackTrace(e));
		String strLog = "---exception--"+Format.DateTimeSSSFormat.format(new Date())+"---\r\n" +logCode+"\t" + sbMsg.toString() + "---------------------\r\n";
		addLog(strLog, false, false);
	}
	
	private void addLog(String pLog, boolean pAddTime, boolean toConsole){
		String logStr;
		if(pAddTime){
			logStr = Format.DateTimeSSSFormat.format(new Date()) + "\t" + pLog + "\r\n";
		}else{
			logStr = pLog + "\r\n";
		}
		if(sbLog.length() > 512000){
			FGBiz.limitMsg.addConsole("startLog", sbLog.toString());
			sbLog = new StringBuffer(2048);
		}
		sbLog.append(logStr);
		if(toConsole){
			System.out.print(logStr);
		}
	}
	
	public String getLog(){
		return sbLog.toString();
	}
}
